package com.yu.hu

import android.app.Application
import android.content.Intent
import android.os.Process
import com.yu.hu.base.util.Logger
import dagger.hilt.android.HiltAndroidApp
import okio.buffer
import okio.sink
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.system.exitProcess

/**
 * huyu create
 * 2025/10/31 14:42
 */
@HiltAndroidApp
class MainApplication : Application() {

    private var tag = "MainApplication"

    override fun onCreate() {
        super.onCreate()
        tag = getString(R.string.app_name)

        Thread.setDefaultUncaughtExceptionHandler { _, throwable ->
            // 1. 写入日志
            Logger.e(tag, "uncaughtException:${throwable.message}", throwable)
            writeThrowable(throwable)

            // 2. 重启 App
            restart()

            // 3. 结束当前进程
            Process.killProcess(Process.myPid())
            exitProcess(1)
        }
    }

    private fun restart() {
        //https://juejin.cn/post/7207743145999024165 用的评论中的方案
        val intent = packageManager.getLaunchIntentForPackage(packageName)
        if (intent != null) {
            val restartActivityIntent = Intent.makeRestartActivityTask(intent.component)
            startActivity(restartActivityIntent)
        } else {
            Logger.e(tag, "restart failed: intent is null")
        }
    }

    private fun writeThrowable(throwable: Throwable): Result<File> {
        val timestamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault())
            .format(Date())
        val file = File(filesDir, "crash/$timestamp")
        if (file.parentFile?.exists() == false) file.parentFile?.mkdirs()
        return runCatching {
            file.sink().buffer().use { sink ->
                sink.writeUtf8("Time: $timestamp\n")
                sink.writeUtf8("Exception: ${throwable::class.java.name}\n")
                sink.writeUtf8("Message: ${throwable.message}\n")
                sink.writeUtf8("StackTrace:\n")
                throwable.stackTrace.forEach {
                    sink.writeUtf8("\tat $it \n")
                }
                file
            }
        }
    }
}